package com.xfgg.cloud.boot.config.mysql;

import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import javax.sql.DataSource;

/**
 * @author xfgg
 */
@Configuration
@MapperScan(basePackages = "com.xfgg.cloud.domain.repository.mapper.account", sqlSessionFactoryRef = "AccountSessionFactory")
public class AccountDataSourceConfig {
    @Bean(name = "accountDataSource")
    @Qualifier("accountDataSource")
    public DataSource accountDataSource(@Value("${spring.datasource.account.driver-class-name}") String driver,
                                        @Value("${spring.datasource.account.url}") String url,
                                        @Value("${spring.datasource.account.username}") String userName,
                                        @Value("${spring.datasource.account.password}") String passWord) {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(userName);
        dataSource.setPassword(passWord);
        return dataSource;
    }

    @Bean(name = "AccountSessionFactory")
    public SqlSessionFactory accountSessionFactory(@Qualifier("accountDataSource") DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        return bean.getObject();
    }

    @Bean(name = "accountSessionTemplate")
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("accountDataSource") DataSource dataSource) throws Exception {
        return new SqlSessionTemplate(accountSessionFactory(dataSource));
    }

    @Bean(name = "accountTransactionManager")
    public DataSourceTransactionManager accountTransactionManager(@Qualifier("accountDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}
